<template>
  <div class="user-management">
    <a-page-header title="用户管理" />
    
    <div class="table-actions">
      <a-row :gutter="16">
        <a-col :xs="24" :sm="12" :md="8">
          <a-input-search
            v-model:value="searchQuery"
            placeholder="搜索用户名或邮箱"
            @search="handleSearch"
            allow-clear
          />
        </a-col>
        <a-col :xs="24" :sm="12" :md="8">
          <a-select
            v-model:value="filterStatus"
            placeholder="筛选状态"
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="all">全部用户</a-select-option>
            <a-select-option value="active">活跃用户</a-select-option>
            <a-select-option value="inactive">未激活用户</a-select-option>
            <a-select-option value="staff">管理员</a-select-option>
          </a-select>
        </a-col>
      </a-row>
    </div>
    
    <a-table
      :columns="columns"
      :data-source="users"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="record.is_active ? 'green' : 'red'">
            {{ record.is_active ? '活跃' : '未激活' }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'role'">
          <a-tag :color="record.is_staff ? 'blue' : 'default'">
            {{ record.is_staff ? '管理员' : '普通用户' }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'subscription'">
          <a-tag :color="getSubscriptionColor(record.subscription)">
            {{ record.subscription ? record.subscription.pricing_plan.name : '免费用户' }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="viewUserDetails(record)">
              详情
            </a-button>
            <a-button type="link" @click="editUser(record)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除此用户吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteUser(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 用户详情抽屉 -->
    <a-drawer
      title="用户详情"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      width="600"
    >
      <a-descriptions bordered v-if="selectedUser">
        <a-descriptions-item label="用户名" span="3">
          {{ selectedUser.username }}
        </a-descriptions-item>
        <a-descriptions-item label="姓名" span="3">
          {{ `${selectedUser.first_name || ''} ${selectedUser.last_name || ''}`.trim() || '未设置' }}
        </a-descriptions-item>
        <a-descriptions-item label="邮箱" span="3">
          {{ selectedUser.email }}
        </a-descriptions-item>
        <a-descriptions-item label="注册时间" span="3">
          {{ formatDate(selectedUser.date_joined) }}
        </a-descriptions-item>
        <a-descriptions-item label="最后登录" span="3">
          {{ selectedUser.last_login ? formatDate(selectedUser.last_login) : '从未登录' }}
        </a-descriptions-item>
        <a-descriptions-item label="状态" span="3">
          <a-tag :color="selectedUser.is_active ? 'green' : 'red'">
            {{ selectedUser.is_active ? '活跃' : '未激活' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="角色" span="3">
          <a-tag :color="selectedUser.is_staff ? 'blue' : 'default'">
            {{ selectedUser.is_staff ? '管理员' : '普通用户' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="会员方案" span="3">
          <a-tag :color="getSubscriptionColor(selectedUser.subscription)">
            {{ selectedUser.subscription ? selectedUser.subscription.pricing_plan.name : '免费用户' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="会员到期时间" span="3">
          {{ selectedUser.subscription ? formatDate(selectedUser.subscription.end_date) : '无' }}
        </a-descriptions-item>
        <a-descriptions-item label="提示词数量" span="3">
          {{ selectedUser.prompt_count || 0 }}
        </a-descriptions-item>
      </a-descriptions>
      
      <div class="drawer-actions">
        <a-button type="primary" @click="editUser(selectedUser)">
          编辑用户
        </a-button>
      </div>
    </a-drawer>
    
    <!-- 编辑用户对话框 -->
    <a-modal
      :title="isNewUser ? '添加用户' : '编辑用户'"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="modalVisible = false"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="userForm"
        :rules="userFormRules"
        layout="vertical"
        ref="userFormRef"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="userForm.username" />
        </a-form-item>
        
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="userForm.email" />
        </a-form-item>
        
        <a-form-item label="姓" name="first_name">
          <a-input v-model:value="userForm.first_name" />
        </a-form-item>
        
        <a-form-item label="名" name="last_name">
          <a-input v-model:value="userForm.last_name" />
        </a-form-item>
        
        <a-form-item label="密码" name="password" v-if="isNewUser">
          <a-input-password v-model:value="userForm.password" />
        </a-form-item>
        
        <a-form-item label="状态" name="is_active">
          <a-switch v-model:checked="userForm.is_active" />
        </a-form-item>
        
        <a-form-item label="管理员权限" name="is_staff">
          <a-switch v-model:checked="userForm.is_staff" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

// 定义类型接口





// 假设这些是从API导入的
const getUsers = async (params) => {
  // 模拟API调用
  return {
    results: [
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        first_name: '管理',
        last_name: '员',
        is_active: true,
        is_staff: true,
        date_joined: '2023-01-01T00:00:00Z',
        last_login: '2023-06-01T12:30:00Z',
        subscription: {
          pricing_plan: {
            name: '高级会员',
            tier: 'premium'
          },
          end_date: '2023-12-31T00:00:00Z'
        },
        prompt_count: 120
      },
      {
        id: 2,
        username: 'user1',
        email: 'user1@example.com',
        first_name: '张',
        last_name: '三',
        is_active: true,
        is_staff: false,
        date_joined: '2023-02-15T00:00:00Z',
        last_login: '2023-05-20T08:45:00Z',
        subscription: {
          pricing_plan: {
            name: '基础会员',
            tier: 'basic'
          },
          end_date: '2023-08-15T00:00:00Z'
        },
        prompt_count: 45
      },
      {
        id: 3,
        username: 'user2',
        email: 'user2@example.com',
        first_name: '李',
        last_name: '四',
        is_active: false,
        is_staff: false,
        date_joined: '2023-03-10T00:00:00Z',
        last_login: null,
        subscription: null,
        prompt_count: 0
      }
    ],
    count: 3
  };
};

const updateUser = async (userId, userData) => {
  // 模拟API调用
  console.log('更新用户:', userId, userData);
  return { ...userData, id: userId };
};

const createUser = async (userData) => {
  // 模拟API调用
  console.log('创建用户:', userData);
  return { ...userData, id: Date.now() };
};

const deleteUserApi = async (userId) => {
  // 模拟API调用
  console.log('删除用户:', userId);
  return true;
};

export default {
  name: 'UserManagement',
  setup() {
    interface User {
      id: number;
      username: string;
      email: string;
      is_active: boolean;
      is_staff: boolean;
      date_joined: string;
      last_login: string | null;
      subscription: Subscription | null;
    }
    
    interface Subscription {
      id: number;
      plan: PricingPlan;
      status: string;
      start_date: string;
      end_date: string;
    }
    
    interface PricingPlan {
      id: number;
      name: string;
      price: number;
      billing_cycle: string;
    }
    
    interface UserForm {
      username: string;
      email: string;
      password?: string;
      is_active: boolean;
      is_staff: boolean;
    }
    
    interface TableParams {
      current: number;
      pageSize: number;
      total: number;
      showSizeChanger: boolean;
      pageSizeOptions: string[];
    }
    
    const users = ref([]);
    const loading = ref(false);
    const searchQuery = ref('');
    const filterStatus = ref('all');
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100']
    });
    
    const drawerVisible = ref(false);
    const selectedUser = ref(null);
    
    const modalVisible = ref(false);
    const confirmLoading = ref(false);
    const isNewUser = ref(false);
    const userFormRef = ref(null);
    
    const userForm = reactive({
      username: '',
      email: '',
      first_name: '',
      last_name: '',
      password: '',
      is_active: true,
      is_staff: false
    });
    
    const userFormRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value) => {
          if (isNewUser.value && !value) {
            return Promise.reject('请输入密码');
          }
          return Promise.resolve();
        }}
      ]
    };
    
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
        sorter: true
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email'
      },
      {
        title: '注册时间',
        dataIndex: 'date_joined',
        key: 'date_joined',
        sorter: true,
        render: (text) => formatDate(text)
      },
      {
        title: '状态',
        key: 'status'
      },
      {
        title: '角色',
        key: 'role'
      },
      {
        title: '会员方案',
        key: 'subscription'
      },
      {
        title: '操作',
        key: 'action'
      }
    ];
    
    const fetchUsers = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.current,
          page_size: pagination.pageSize,
          search: searchQuery.value,
          status: filterStatus.value !== 'all' ? filterStatus.value : undefined
        };
        
        const response = await getUsers(params);
        users.value = response.results;
        pagination.total = response.count;
      } catch (error) {
        message.error('获取用户列表失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    const handleSearch = () => {
      pagination.current = 1;
      fetchUsers();
    };
    
    const handleFilterChange = () => {
      pagination.current = 1;
      fetchUsers();
    };
    
    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchUsers();
    };
    
    const viewUserDetails = (user) => {
      selectedUser.value = user;
      drawerVisible.value = true;
    };
    
    const editUser = (user) => {
      isNewUser.value = false;
      userForm.username = user.username;
      userForm.email = user.email;
      userForm.first_name = user.first_name || '';
      userForm.last_name = user.last_name || '';
      userForm.password = '';
      userForm.is_active = user.is_active;
      userForm.is_staff = user.is_staff;
      
      selectedUser.value = user;
      modalVisible.value = true;
    };
    
    const addNewUser = () => {
      isNewUser.value = true;
      userForm.username = '';
      userForm.email = '';
      userForm.first_name = '';
      userForm.last_name = '';
      userForm.password = '';
      userForm.is_active = true;
      userForm.is_staff = false;
      
      modalVisible.value = true;
    };
    
    const handleModalOk = async () => {
      try {
        await userFormRef.value.validate();
        
        confirmLoading.value = true;
        
        if (isNewUser.value) {
          await createUser(userForm);
          message.success('用户创建成功');
        } else {
          await updateUser(selectedUser.value.id, userForm);
          message.success('用户更新成功');
        }
        
        modalVisible.value = false;
        fetchUsers();
      } catch (error) {
        console.error('表单验证失败:', error);
      } finally {
        confirmLoading.value = false;
      }
    };
    
    const deleteUser = async (userId) => {
      try {
        await deleteUserApi(userId);
        message.success('用户删除成功');
        fetchUsers();
      } catch (error) {
        message.error('删除用户失败');
        console.error(error);
      }
    };
    
    const getSubscriptionColor = (subscription | null): string => {
      if (!subscription) return 'default';
      
      const tier = subscription.pricing_plan.tier;
      switch (tier) {
        case 'basic':
          return 'blue';
        case 'pro':
          return 'purple';
        case 'premium':
          return 'gold';
        default:
          return 'default';
      }
    };
    
    const formatDate = (dateString: string): string => {
      try {
        return format(new Date(dateString), 'yyyy-MM-dd HH:mm', { locale: zhCN });
      } catch (e) {
        return dateString;
      }
    };
    
    onMounted(() => {
      fetchUsers();
    });
    
    return {
      users,
      loading,
      searchQuery,
      filterStatus,
      pagination,
      columns,
      drawerVisible,
      selectedUser,
      modalVisible,
      confirmLoading,
      isNewUser,
      userForm,
      userFormRef,
      userFormRules,
      handleSearch,
      handleFilterChange,
      handleTableChange,
      viewUserDetails,
      editUser,
      addNewUser,
      handleModalOk,
      deleteUser,
      getSubscriptionColor,
      formatDate
    };
  }
};
</script>

<style scoped>
.user-management {
  padding: 24px;
}

.table-actions {
  margin-bottom: 16px;
}

.drawer-actions {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 4px 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 12px;
  }
  
  .table-actions {
    margin-bottom: 12px;
  }
  
  .table-actions .ant-row {
    row-gap: 12px;
  }
}

@media (max-width: 576px) {
  .drawer-content {
    padding: 12px;
  }
}
</style>